<?php
namespace app\index\controller;
use stock\other\PageSql;
use \think\Request;
use think\Db; 
use stock\other\Trackingmore;
use stock\other\RedisDemo;
class Goods extends \app\index\controller\Common
{
	
	public function goods_show(){
		$request = request()->param();
		$data=array();

		if(isset($request['id'])){
			$id=(int)$request['id'];
			if($id){

				$goodsObj=Db::name('goods');
				if(1==$_SESSION['admin_id']){
					$sql='id='.$id;
				}else{
					$sql='id='.$id.' and (branch='.(int)$_SESSION['admin_id'].' or part='.(int)$_SESSION['admin_id'].')';
				}
				$data=$goodsObj->where($sql)->find();

				//$data['track']=$this->tracklist('81108898713');//($data['order_No']);
				$data['track']=$this->tracklist($data['order_No']);

				$categObj=Db::name('category');

				$part_id=$data['part'] ? (int)$data['part'] : (int)$data['branch'];
				
				$catedata=$categObj->where('id='.$part_id)->field('name')->find();
				$this->assign('data',$data);				
				$this->assign('cate_name',$catedata['name']);
				return $this->fetch();	
			}
		}	
	}
	public function order_no_check(){
		$request = request()->param();
		
		if(empty($request['ono'])){
			exit(json_encode(array('status'=>0)));
		}
		$where="order_No ='".addslashes(trim($request['ono']))."'";
		if(!empty($request['oid'])){
			$where .=' and id !='.(int)$request['oid'];
		}
		$catedata=Db::name('goods')->where($where)->field('id')->find();
		if($catedata){
			exit(json_encode(array('status'=>1)));
		}
		exit(json_encode(array('status'=>0)));
	}
	public function goods_add(){
		$request = request()->param();
		$data=array();

		if(isset($request['id'])){
			$id=(int)$request['id'];
			if($id){

				$goodsObj=Db::name('goods');
				$data=$goodsObj->where('id='.$id.' and from_branch='.(int)$_SESSION['admin_id'])->find();				
			}
		}

		$categObj=Db::name('category');
		
		$catedata=$categObj->where('parent_id=0 and id!='.$_SESSION['admin_id'])->order('id desc')->select();
		$catedata1=$categObj->where('parent_id >0 and id!='.$_SESSION['admin_id'])->order('id desc')->select();
		$this->assign('data',$data);				
		$this->assign('cate_list',$catedata);
		$this->assign('cate_list1',$catedata1);
		return $this->fetch();
	}
	public function goods_deal_add1(){
		$request = request()->param();
	    if(isset($request['id'])){
	    	$id=(int)$request['id'];
	    }		
	    $data['status']=$request['status'];
	    $data['finish_time']=time();
	    if($data['status']==1)
		$re=Db::name('goods')->where("id=".$id." and (branch=".$_SESSION['admin_id'].' or part='.$_SESSION['admin_id'].')')->update($data);

		if($re){
			$this->success('收件成功', '/Index/goods/goods_list');
		}else{
			$this->error('收件失败，请重试');
		}	
	}	
	public function goods_deal_add(){
		$request = request()->param();
	    $data['order_No']=$request['order_No'];
	    $data['e_type']=(int)$request['e_type'];
	    $data['content']=addslashes($request['content']);
	    $data['branch']=(int)$request['branch'];
	    $data['create_time']=time();
	    $data['from_branch']=(int)$_SESSION['admin_id'];
	    if(1==$data['branch']){	
	        $data['part']=(int)$request['part'];  	
	    }
	    $id='';
	    if(isset($request['id'])){
	    	$id=(int)$request['id'];
	    }	    

		if($id){				
			unset($data['create_time']);

			$re=Db::name('goods')->where("id=".$id." and from_branch=".$data['from_branch'])->update($data);
		}else{
			$d_status=Db::name('goods')->where("order_No='".$data['order_No']."'")->find();
			if(empty($d_status))
				$re=Db::name('goods')->insertGetId($data);
		}
		$this->deliver_create(trim($data['order_No']));
		if($re){
			$this->success('快件添加成功', '/Index/goods/goods_list');
		}else{
			$this->error('添加失败，请重试');
		}	
	}
	public function goods_de(){
		$request = request()->param();
		$id=(int)$request['id'];
		if($id){
			$goodsObj=Db::name('goods');
			$data['status']=2;
			$goodsObj->where("id=".$id." and from_branch=".$_SESSION['admin_id']." and status=0")->update($data);
			$this->success('快件已删除', '/Index/goods/goods_list');			
		}else{
			$this->error('删除失败,请重试');
		}
	}
	public function goods_list(){
		$goodsObj=Db::name('goods');
		if(1==(int)$_SESSION['admin_id']){
			$sql='a.status!=2';

		}else{
			$sql='a.status!=2 and (a.from_branch='.$_SESSION['admin_id'].' or a.branch='.$_SESSION['admin_id'].' or a.part='.$_SESSION['admin_id'].')';
		}
		$request = request()->param();
		if(isset($request['status'])){
			$status=$request['status']==2 ? 0 : 1;
			$sql .=" and a.status=".$status;
			$this->assign('status', $request['status']);
		}	
		if(isset($request['name'])){
			$sql .=" and a.order_No like '%".addslashes(trim($request['name']))."'";
			$this->assign('name', $request['name']);
		}
		$_end=$_start=date('Y').'-'.date('m').'-'.date('d');

		if(isset($request['start'])){
			$_start=$request['start'];
			$_end=$request['end'];
			$sql .=" and a.create_time between '".strtotime($_start.' 00:00:00')."' and ".strtotime($_end.' 00:00:00');
		}		
		$list = Db::table('wx_goods')->alias('a')->where($sql)->join('wx_category b','a.branch=b.id')->field('a.*,b.name bname')->order("a.id desc")->paginate(66);//echo Db::name('goods')->getLastSql();exit;
		//$list=$goodsObj->where($sql)->order("id desc")->paginate(66);
		//print_r($list);exit;
		$page = $list->render();
		$list1=$list->toArray();
		$datar=$list1['data'];//print_r($datar);
		$trackinforr_all=$this->tracklist_new();//print_r($trackinfo);exit;
		$trackinforr=$trackinforr_all['data'];
		$time=$trackinforr_all['time'];
		if($datar){
			foreach($datar as $key => $value){
				$value['track']=$trackinforr[$value['order_No']];
				$datar[$key]=$value;
				//echo $value['order_No'];
				//print_r($this->tracklist($value['order_No']));
				//print_r($value);
			}
		}  
        // 模板变量赋值
        $this->assign('time', $time);
        $this->assign('start', $_start);
        $this->assign('end', $_end);
        $this->assign('list', $datar);
        $this->assign('page', $page); 		
		return $this->fetch();
	}
	public function deliver_status(){
		//$key='d8443d28-bcd3-4f4b-9ce9-6302ec7503b6';
		$type='lbcexpress';
		
		$request = request()->param();
		//if($request['order_No']){
			$track = new Trackingmore;
			$track = $track->getRealtimeTrackingResults($type,'81108898471');print_r($track);
		//}
/**
Array ( [meta] => Array ( [code] => 200 [type] => Success [message] => Success ) [data] => Array ( [items] => Array ( [0] => Array ( [id] => 3c9adc3a76559b8fcbbd714fe75d9d98 [tracking_number] => 81108898713 [carrier_code] => lbcexpress [status] => transit [original_country] => [itemTimeLength] => 7 [origin_info] => Array ( [weblink] => http://www.lbcexpress.com/ [phone] => [carrier_code] => lbcexpress [trackinfo] => Array ( [0] => Array ( [Date] => 2017-07-28 00:00 [StatusDescription] => Released to authorized representative SG SABALONGA 07/28/2017. [Details] => ) [1] => Array ( [Date] => 2017-07-28 00:00 [StatusDescription] => Ready for delivery. Please expect delivery within the day. [Details] => ) [2] => Array ( [Date] => 2017-07-28 00:00 [StatusDescription] => Arrived at CAUAYAN DELIVERY HUB. [Details] => ) [3] => Array ( [Date] => 2017-07-27 00:00 [StatusDescription] => Arrived at CAUAYAN DELIVERY HUB. [Details] => ) [4] => Array ( [Date] => 2017-07-26 00:00 [StatusDescription] => Forwarded to CAUAYAN DELIVERY HUB. [Details] => ) [5] => Array ( [Date] => 2017-07-26 00:00 [StatusDescription] => Arrived at CENTRAL EXCHANGE HANGAR. [Details] => ) [6] => Array ( [Date] => 2017-07-26 00:00 [StatusDescription] => Arrived at LBC SOLUTIONS DELIVERY. [Details] => ) ) ) [destination_info] => [lastEvent] => Released to authorized representative SG SABALONGA 07/28/2017.,2017-07-28 00:00 [lastUpdateTime] => 2017-07-28 00:00 ) ) ) )
*/		
	}
	private function get_trackinfo($num=''){
		$result['trackinfo']=array(
			'0' => Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ),
			'1' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ),
			'2' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ),
			'3' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ),
			'4' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ), 
			'5' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' ),
			'6' =>  Array ( 'Date' => '2017-07-28 00:00' ,'StatusDescription' => 'Released to authorized representative SG SABALONGA 07/28/2017.' ,'Details' =>'' )
			);
		$str='';
		foreach ($result['trackinfo'] as $key => $value) {
			$str .=$value['Date'].'&nbsp;&nbsp;'.$value['StatusDescription'].'<br>';
		}
		return $str;			
	}
	public function deliver_create($num){
		$type='lbcexpress';
		$track = new Trackingmore;
		$extraInfo['title']          = 'iphone6';
		$extraInfo['customer_name']  = 'charse chen';
		$extraInfo['customer_email'] = 'chasechen@gmail.com';
		$extraInfo['order_id']       = time();
		$track = $track->createTracking($type,$num,$extraInfo);//print_r($track);		
	}
	public function deliver_create1(){
		$type='lbcexpress';
		$track = new Trackingmore;
		$extraInfo['title']          = 'iphone6';
		$extraInfo['customer_name']  = 'charse chen';
		$extraInfo['customer_email'] = 'chasechen@gmail.com';
		$extraInfo['order_id']       = time();
		$track = $track->createTracking($type,'81108898473',$extraInfo);print_r($track);		
	}
	public function deliver_list(){
		$track = new Trackingmore;
		$page = 1;
		$limit = 2000;
		$createdAtMin = time() - 8*24*60*60;
		$createdAtMax = time();
		$track = $track->getTrackingsList($page,$limit,$createdAtMin,$createdAtMax);//print_r($track);exit;
		return $track;		
	}
	public function deliver_list1(){
		$track = new Trackingmore;
		$page = 1;
		$limit = 50;
		$createdAtMin = time() - 10*3*7*24*60*60;
		$createdAtMax = time();
		$track = $track->getTrackingsList($page,$limit,$createdAtMin,$createdAtMax);print_r($track);exit;
		return $track;		
	}
	public function tracklist($num){
		$redis=new RedisDemo();
		$key='trackinfo_new';
		$result=$redis->get($key);
		if($result){
			$result=unserialize($result);
		}else{
			$result=$this->deliver_list();
			if('Success'==$result['type']){
				$redis->set($key,serialize($result),60*60*5);
			}
		}
		//$num='81108898472';
		$trackinfo='';echo '<br>'.$num.'<br>';
		if($result['data']['items']){
			$_result=$result['data']['items'];//print_r($_result);
			foreach ($_result as $key1 => $value1) {
			
				if(trim($num)==trim($value1['tracking_number'])){echo $value1['tracking_number'].'++++'.'aaaaa'.'<br>';
					
					if(!empty($value1['origin_info']['trackinfo'])){
						
						foreach ($value1['origin_info']['trackinfo'] as $k => $v) {
							$trackinfo .=$v['Date'].'&nbsp;&nbsp;'.$v['StatusDescription'].'<br>';
						}						
					}else{
						$trackinfo .='No Data';
					}
					break;					
				}
			
				
			}
		}
		return $trackinfo;
	}
	public function tracklist_new(){
		$redis=new RedisDemo();
		$key='trackinfo_new_info_list';
		$result1=$redis->get($key);
		$new_result=array();
		if($result1){
			$result_new=unserialize($result1);
		}else{
			$result=$this->deliver_list();
			if('Success'==$result['meta']['type']){
				if($result['data']['items']){
					$_result=$result['data']['items'];//print_r($_result);
					$result1=array();
					foreach ($_result as $key1 => $value1) {
						$new_key=trim($value1['tracking_number']);
						
						$trackinfo='';
						if(!empty($value1['origin_info']['trackinfo'])){
							
							foreach ($value1['origin_info']['trackinfo'] as $k => $v) {
								$trackinfo .=$v['Date'].'&nbsp;&nbsp;'.$v['StatusDescription'].'<br>';
							}						
						}else{
							$trackinfo .='No Data';
						}
						$result1[$new_key]['track']=$trackinfo;
						$result1[$new_key]['status_text']=$value1['status'];
					}
				}
				$result_new['data']=$result1;
				$result_new['time']=date('H:i:s');
				$redis->set($key,serialize($result_new),3*60);
			}
		}
		return $result_new;
	}
	public function carrier_list(){
		$track = new Trackingmore;
		$trackingNumber = '57032942';
		$track = $track->detectCarrier($trackingNumber);print_r($track);		
		/*
		$track = new Trackingmore;
		$track = $track->getCarrierList();print_r($track);
		*/
	}
	public function track_by_num(){
		$request = request()->param();
		$num=trim($request['num']);
		$type='lbcexpress';
		if($num){
			$track = new Trackingmore;
			$track = $track->getRealtimeTrackingResults($type,$num);print_r($track);	

		}
	}	
}	